import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Browser, BrowserHrm, Reply, TabPage, RouteLayout, Upload } from 'weaver-mobile-page';
import { withRouter } from 'react-router-dom';
import { createForm } from 'rc-form';
import {
  Tools,
  Toast,
  Icon,
  Button,
  Bubble,
  InputItem,
  List,
  DatePicker,
  FilePicker,
  Accordion,
  TextareaItem,
} from 'weaver-mobile';
import { Files } from '../coms'
import { DateDiffDays, opendoc, downloadsDoc } from '../../../util'
import { WrFeedback } from '../../../public';

const getLabel = Tools.getLabel;
const { DatePickerInput } = DatePicker;
const { FormItem } = List;
const ButtonGroup = RouteLayout.ButtonGroup;

/*
详情页面
*/
@inject('planDetailStore', 'planViewStore')
@withRouter
@observer
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detailid: '',
      type1: '1', //月还是周
      datatype: 3, //3总结2计划
      resourceid: '',
      canedit: false,
      noEditFields: [], //计划内不可以编辑的属性
      tabKey: 1,
      layoutButtons: [],
      inOrOut: ''
    };
    this.store = this.props.planDetailStore;
  }

  componentWillMount() {
    //初始化
    let search = this.props.location.search.replace('?', '');
    let params = search.split('&')
    let canedit, datatype
    if (params.length > 1) {
      //search: `${detailid}&${3}&${this.store.type1}&${this.store.resourceid}&${canedit}&${noEditFields.join('^')}`
      let detailid = params[0]
      datatype = params[1]
      let type1 = params[2]
      let resourceid = params[3]
      canedit = params[4] === 'true'
      let noEditFields = params[5] && params[5].split("^")
      let inOrOut = params[6]
      this.setState({ detailid, type1, datatype, resourceid, noEditFields, canedit, inOrOut })
    } else {
      let detailid = params[0]
      this.setState({ detailid })
    }

    let detailQuery = {
      plandetailid: params[0],
      datatype: datatype
    };
    this.store.getDetailView(detailQuery).then(res => {
      if (!res.api_status || res.api_status == '0') {
        this.props.history.go(-1)
        return
      }
      this.initData();
    })
    this.initLayoutButtons(canedit)
  }
  initLayoutButtons = (canedit) => {
    let { history } = this.props
    let buttons = []
    if (canedit) {
      buttons.push({
        key: 'clear',
        text: getLabel(201, '取消'),
        onClick: () => {history.go(-1);this.store.reset()},
      })
      buttons.push({
        key: 'submit',
        text: getLabel('826', '确定'),
        onClick: () => this.saveDetail(),
        type: 'primary',
      })
    } else {
      buttons.push({
        key: 'clear',
        text:getLabel(309,'关闭'),
        onClick: () => {history.go(-1);this.store.reset()},
        type: 'primary',
      })
    }


    this.setState({
      layoutButtons: buttons
    })
  }


  render() {
    const prefixClass = 'workrelate-mobile-plan-planview-detail-';
    let { detailMapList, detailMapData, isLoading } = this.store;
    const { tabKey, canedit, detailid } = this.state
    const filearray = detailMapData.filearray ? detailMapData.filearray : [];
    let {
      taskBrowser,
      taskBrowserValue,
      docBrowser,
      docBrowserValue,
      wfBrowser,
      wfBrowserValue,
      customerBrowserValue,
      customerBrowser,
      projectBrowserValue,
      projectBrowser,
      setState,
      fileStore,
      detailFileStore,
      detailFiles,
      detailFileIds,
      files, maxsize,category
    } = this.props.planDetailStore;
    const tabProps = {
      onTabClick: (tab) => {
        this.setState({ tabKey: tab.key })
      },
      onChange: (tab) => {
      },
    };
    const tabs = [
      { title: getLabel('382624', '查看明细'), key: 1 },
      { title: getLabel(33956, '意见反馈'), key: 2 },
    ]
    return (
      <div
        className="wm-route-layout"
      >
        {isLoading ? "" :
          <div className={`${prefixClass}container workrelate-roll`} >
            <div className={`${prefixClass}tab-container`}>
              <TabPage
                className={`${prefixClass}tabpage`}
                tabs={tabs}
                tabProps={tabProps}
                defaultTabBarProps={{ page: 4 }}
              />
            </div>

            {
              tabKey == 1 && <div className="roll workrelate-condition">
                <Accordion defaultActiveKey="0">
                  <Accordion.Panel header={getLabel(1361, '基本信息')} className="custom-header">
                <div className="workrelate-mobile-plan-planview-detail-base">


                    {detailMapList &&
                      detailMapList.map(p => {
                        return this.renderByInputType(
                          p.inputtype,
                          p.fieldname,
                          p.showname,
                          p.ismust
                        );
                      })}

                </div>
                  </Accordion.Panel>
                </Accordion>
                <Accordion defaultActiveKey="0">
                  <Accordion.Panel header={getLabel(22078, '相关信息')} className="custom-header">
                    {/* 任务 文档 流程 客户 项目 */}
                    <List>
                      <Browser
                        placeholder={canedit ? getLabel(18214, '请选择') : " "}
                        className={canedit ? '' : 'hide-icon'}
                        viewAttr={canedit ? 2 : 1}
                        label={getLabel(1332, '任务')}
                        store={taskBrowser}
                        hasAdvanceSerach
                        isSingle={false}
                        type={'wrltsk'}
                        onChange={(ids, names, array) => this.onBrowserChange("taskids", 'taskarray', "taskBrowserValue", ids, names, array)}
                        valueArray={taskBrowserValue ? taskBrowserValue : []}
                      />
                    </List>
                    <List>
                      <Browser
                        placeholder={canedit ? getLabel(18214, '请选择') : " "}
                        className={canedit ? '' : 'hide-icon'}
                        viewAttr={canedit ? 2 : 1}
                        label={getLabel(58, '文档')}
                        store={docBrowser}
                        hasAdvanceSerach
                        isSingle={false}
                        type={'9'}
                        onChange={(ids, names, array) => this.onBrowserChange("docids", 'docarray', "docBrowserValue", ids, names, array)}
                        valueArray={docBrowserValue ? docBrowserValue : []}
                      />
                    </List>
                    <List>
                      <Browser
                        placeholder={canedit ? getLabel(18214, '请选择') : " "}
                        className={canedit ? '' : 'hide-icon'}
                        viewAttr={canedit ? 2 : 1}
                        label={getLabel(18015, '流程')}
                        store={wfBrowser}
                        hasAdvanceSerach
                        isSingle={false}
                        type={'16'}
                        onChange={(ids, names, array) => this.onBrowserChange("wfids", 'wfarray', "wfBrowserValue", ids, names, array)}
                        valueArray={wfBrowserValue ? wfBrowserValue : []}
                      />
                    </List>

                    <List>
                      <Browser
                        placeholder={canedit ? getLabel(18214, '请选择') : " "}
                        className={canedit ? '' : 'hide-icon'}
                        viewAttr={canedit ? 2 : 1}
                        label={getLabel(136, '客户')}
                        store={customerBrowser}
                        hasAdvanceSerach
                        isSingle={false}
                        type={'7'}
                        onChange={(ids, names, array) => this.onBrowserChange("crmids", 'crmarray', "customerBrowserValue", ids, names, array)}
                        valueArray={customerBrowserValue ? customerBrowserValue : []}
                      />
                    </List>
                    <List>
                      <Browser
                        placeholder={canedit ? getLabel(18214, '请选择') : " "}
                        className={canedit ? '' : 'hide-icon'}
                        viewAttr={canedit ? 2 : 1}
                        label={getLabel(101, '项目')}
                        store={projectBrowser}
                        hasAdvanceSerach
                        isSingle={false}
                        type={'8'}
                        onChange={(ids, names, array) => this.onBrowserChange("projectids", 'projectarray', "projectBrowserValue", ids, names, array)}
                        valueArray={projectBrowserValue ? projectBrowserValue : []}
                      />
                    </List>
                    <List>
                      <List.FormItem
                        label={getLabel(156, '附件')}
                        noBorder
                        line
                        //required={!value && isRequire}
                        content={<div className={`${prefixClass}files`}><Upload
                          uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                          viewAttr={canedit ? 2 : 1}
                          store={detailFileStore}
                          datas={detailFiles}
                          editable={canedit}
                          onChange={this.onFilesChange}
                          maxUploadSize={maxsize}
                          showUploader={false}
                          showUploadTime={false}
                          onItemClick={(file, index, files) => {
                            opendoc(file.id, detailid, 4,detailid)
                          }}
                          onFileLoad={(file) => {
                            downloadsDoc(file.id, file.imagefileid, detailid, 4,detailid)
                          }}
                        /></div>}
                      />
                    </List>

                  </Accordion.Panel>
                </Accordion>
              </div>
            }

            {tabKey === 2 && <div className={`${prefixClass}feedback roll`}>
              <WrFeedback
                fbList={this.store.detailFbList}
                fbReplyStore={this.store.detailReplyStore}
                onSubmit={(datas) => {
                  const { text } = datas
                  this.saveFeedback(text)
                  // this.store.saveFeedback(text)
                }}
                showReply={false}
              />
            </div>}
            {tabKey === 2 && <div className={`${prefixClass}reply`} >
              <Reply
                store={this.store.detailReplyStore}
                //   leftConfig={leftConfig}
                placeholder={getLabel('83869', '请输入')}
                showOutInput
                onSubmit={(datas) => {
                  const { text } = datas
                  this.saveFeedback(text)
                }} // 提交的时候，如果需要清空数据，调用store的doClear方法
              />
            </div>
            }

          </div>

        }
        <ButtonGroup data={tabKey === 1 ? this.state.layoutButtons : []} isButton={true} />
      </div>
    )




  }
  //初始化数据
  initData = () => {
    //初始化相关链接
    this.initRelateValue();
  };
  //初始化相关链接
  initRelateValue = () => {
    this.store.reset()
    let { detailMapData } = this.store;
    let { setState, reset } = this.props.planDetailStore;
    setState({
      taskBrowserValue: detailMapData['taskarray']?detailMapData['taskarray']:[],
      docBrowserValue: detailMapData['docarray']?detailMapData['docarray']:[],
      projectBrowserValue: detailMapData['projectarray']?detailMapData['projectarray']:[],
      customerBrowserValue: detailMapData['crmarray']?detailMapData['crmarray']:[],
      wfBrowserValue: detailMapData['wfarray']? detailMapData['wfarray']:[],
    });
  };
  //附件变动事件
  onFilesChange = (ids, files) => {
    this.store.setState({ detailFiles: files, detailFileIds: ids.toString() })

  }
  //日期变动时间  开始时间不能小于结束时间  自动计算天数
  onDateChange = (fieldName) => {
    let values = this.props.form.getFieldsValue()
    if (values['begindate2'] && values['enddate2']) {
      let days = DateDiffDays(values['begindate2'], values['enddate2'])
      if (days < 0) {
        Bubble.warning(getLabel(16721, '开始时间不能大于结束时间'));
        let fields = {}
        fields[fieldName] = this.store.detailMapData[fieldName]
        this.props.form.setFieldsValue(fields)
      } else {
        this.props.form.setFieldsValue({ 'days2': days })
      }
    }
    if (values['begindate1'] && values['enddate1']) {
      let days = DateDiffDays(values['begindate1'], values['enddate1'])
      if (days < 0) {
        Bubble.warning(getLabel(16721, '开始时间不能大于结束时间'));
        let fields = {}
        fields[fieldName] = this.store.detailMapData[fieldName]
        this.props.form.setFieldsValue(fields)
      } else {

        this.props.form.setFieldsValue({ 'days1': days })
      }
    }
  }

  //根据inputtype渲染输入框
  renderByInputType = (inputType, fieldname, showname, ismust) => {
    let { canedit, noEditFields } = this.state
    ismust = ismust == '1'
    //如果能编辑 并且计划内的 
    if (canedit && noEditFields) {
      canedit = noEditFields.indexOf(fieldname) > -1 ? false : true
      ismust = canedit && ismust
    }
    //标题必须必填
    if(fieldname=='name'){ismust = true}
    const { getFieldProps } = this.props.form;
    let { detailMapData } = this.store;
    let com;
    let _ = this
    if (inputType == 3) {
      com = (
        <List key={fieldname}>
          <span>
            <FormItem
              label={showname}
              line
              content={(<DatePickerInput
                editable={canedit}
                disabled={!canedit}
                mode="date"
                required={ismust}
                onOk={() => { this.onDateChange(fieldname) }}
                {...getFieldProps(
                  fieldname,
                  {
                    rules: [{ required: ismust }],
                    initialValue: detailMapData[fieldname]
                  },
                )}
                placeholder={canedit ? getLabel(18214, '请选择') : ''}
              />)}
            />
          </span>
        </List>
      );
      return com
    } else if (inputType == 4) {
      com = (
        <InputItem
          editable={canedit}
          {...getFieldProps(
            fieldname,
            {
              rules: [{ required: ismust }],
              initialValue: detailMapData[fieldname]
            },
          )}
          type="number"
          placeholder={canedit ? getLabel('83869', '请输入') : ''}
          ref={el => this[fieldname] = el}
        />
      );
    } else if (inputType == 2) {
      com = (
        <TextareaItem
          editable={canedit}
          {...getFieldProps(
            fieldname,
            {
              rules: [{ required: ismust }],
              initialValue: detailMapData[fieldname]
            },
          )}
          autoHeight
          placeholder={canedit ? getLabel('83869', '请输入') : ''}
        />
      );
    } else {
      com = (
        <InputItem
          editable={canedit}
          {...getFieldProps(
            fieldname,
            {
              rules: [{ required: ismust }],
              initialValue: detailMapData[fieldname]
            },
          )}
          placeholder={canedit ? getLabel('83869', '请输入') : ''}
          ref={el => this[fieldname] = el}
        />
      );
    }

    return (
      <List key={fieldname}>
        <span
          onClick={() => {
            //如果有换行的话，点击任意区域聚焦输入
            if (this[fieldname]) {
              this[fieldname].focus()
            }
          }}
        >
          <FormItem
            extra={canedit && <Icon type="editor" size="xxs" />}
            key={fieldname}
            label={showname}
            // wrap="nowrap"
            required={canedit && ismust && !this.props.form.getFieldsValue()[fieldname]}
            line
            content={com}
          />
        </span>
      </List>
    );
  };
  //browser change event
  onBrowserChange = (fieldName, fieldArrayName, browserValue, ids, names, array) => {
    if(ids){
      ids = ","+ids+","
    }
    this.store.detailMapData[fieldName] = ids
    this.store.detailMapData[fieldArrayName] = array
    let { setState, reset } = this.props.planDetailStore;
    let valueObject = {}
    valueObject[browserValue] = toJS(array)
    setState(valueObject)
  }
  //保存意见反馈
  saveFeedback = (text) => {
    let params = {
      plandetailid: this.state.detailid,
      content: text,
      operation: "add_feedback",
    }
    this.store.saveDetailView(params);
    let c = document.getElementsByClassName("wm-reply-mask")[0]
    if (c) {
      c.parentNode.removeChild(c)
    }
  }

  //保存详情 
  saveDetail = () => {
    let { programid, detailMapData, detailFileIds } = this.store;
    let { detailid, datatype, type1, resourceid, inOrOut } = this.state
    const { docids, crmids, wfids, projectids, taskids, fileids } = detailMapData;
    let params = {
      operation: 'save_detail',
      resourceid,
      plandetailid: detailid,
      dataType: datatype,
      type1: type1,
    };
    this.props.form.validateFields((error, value) => {
      if (error) {
        Bubble.warning(getLabel('509065', '请输入必填项'));
      } else {
        value.id = detailid;
        value.docids = docids;
        value.crmids = crmids;
        value.wfids = wfids;
        value.projectids = projectids;
        value.taskids = taskids;
        value.fileids = detailFileIds;
        let detailData = JSON.stringify([value]);
        params = { ...params, detailData };
        let rs = this.store.saveDetailView(params);
        rs.then(() => {
          this.props.history.push("/planHome/planView/index")
          const { planViewStore } = this.props
          if (planViewStore) {
            if (datatype == 2 && planViewStore.planlist) {
              planViewStore.planlist.map((p, i) => {
                if (p.id == detailid) {
                  planViewStore.planlist[i] = value
                }
              })
            } else if (inOrOut == 'in' && planViewStore.summaryin) {
              planViewStore.summaryin.map((p, i) => {
                if (p.id == detailid) {
                  planViewStore.summaryin[i] = value
                }
              })
            } else if (inOrOut == 'out' && planViewStore.summaryout) {
              planViewStore.summaryout.map((p, i) => {
                if (p.id == detailid) {
                  planViewStore.summaryout[i] = value
                }
              })
            }
          }
        })
      }
    });
  };


}
Detail.defaultProps = {
  canedit: false
};
export default createForm()(Detail);
